package water.com;

import water.com.DaoSupport.DbBase.DbTest;
import water.com.Ioc.WaterBeanRegistryInfo;
import water.com.Log.Log;
import water.com.Log.LogPrint;
import water.com.Log.LogSubject;
import water.com.RequestParse.WaterHttpHandler;
import com.sun.net.httpserver.HttpServer;
import water.com.util.ConfigurationReader;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executors;

public class ServerStarter {
    private static final Map<String,Class<?>> serviceMap;

    /*
     * 注册接口到接口维护映射表中,初始化Ioc容器，Db自检
     */
    static {
        //初始化日志打印框架
        LogSubject logSubject = new LogSubject();
        Log log = Log.getLog();
        new LogPrint(logSubject,log);
        //注册接口到接口映射表中
        serviceMap = new HashMap<>();
        Map<String, Object> core = (Map)ConfigurationReader.getInstance().getValueByKey("server","core");
        try {
            for (Map.Entry<String, Object> entry : core.entrySet()) {
                serviceMap.put(entry.getKey(), Class.forName((String) entry.getValue()));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //初始化Ioc容器
        try {
            WaterBeanRegistryInfo.initRegistryMap();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //DB自检
        DbTest.DBStartTest();
    }


    public void start() throws Exception{
        //读取服务器配置信息 端口号和url
        int port=(int)ConfigurationReader.getInstance().getValueByKey("server", "port");
        String url =(String) ConfigurationReader.getInstance().getValueByKey("server", "serverUrl");
        //创建一个HttpServer实例，并绑定到指定的IP地址和端口号
        HttpServer httpServer = HttpServer.create(new InetSocketAddress(port), 0);
        //创建一个HttpContext，将路径为/talkServer请求映射到WaterHttpHandler处理器
        httpServer.createContext(url, new WaterHttpHandler(serviceMap));
        //设置服务器的线程池对象
        httpServer.setExecutor(Executors.newFixedThreadPool(100));
        //启动服务器
        httpServer.start();
        Log.getLog().info("Water服务器启动成功，等待请求...");
    }

}
